package cn.sciento.farm.devicemanager.gateway.lorawan.config;

import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.InternalService;
import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.JwtCallCredential;
import cn.sciento.farm.devicemanager.lorawan.LoginRequest;
import cn.sciento.farm.devicemanager.lorawan.LoginResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author wumu
 * @version V1.0
 * @date 9/15/18
 * @time 7:27 PM
 */
@Slf4j
@Service
public class JwtManager {

    private volatile String token = "";

    @Autowired
    private InternalService internalService;

    @Value("${loraapp.username}")
    private String username;

    @Value("${loraapp.password}")
    private String password;


    @PostConstruct
    private void post() {
        refreshToken();
    }

    @Scheduled(cron = "0 0 0 * * ? ")
    public void check() {
        refreshToken();
    }


    private void refreshToken() {
        LoginResponse loginResponse = internalService.login(LoginRequest.newBuilder()
                .setUsername(username)
                .setPassword(password)
                .build());
        token = loginResponse.getJwt();
    }


    public JwtCallCredential getToken() {
        JwtCallCredential jwtCallCredential = new JwtCallCredential(token);
        return jwtCallCredential;
    }
}
